iT邦幫忙

2024 iThome 鐵人賽

DAY 6
0

首先來安裝 Expo Notification library。

npx expo install expo-notifications

接著把官方範例複製貼上到自己的 Expo 專案。

import { useState, useEffect, useRef } from 'react';
import { Text, View, Button, Platform } from 'react-native';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import Constants from 'expo-constants';

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: false,
    shouldSetBadge: false,
  }),
});

...

資料來源:Expo - Expo Notifications

滿心歡喜的貼上後,結果看到 IDE 顯示一些錯誤。
https://ithelp.ithome.com.tw/upload/images/20240916/20151956szHATZJ8te.png

從紅框的 Open in Snack 連結點進去看,範例程式碼的 App 檔案副檔名是 .tsx ,而不是 .js
https://ithelp.ithome.com.tw/upload/images/20240916/2015195619yUolqOIo.png

Expo 的 Notification 文件只提供 TypeScript 範例,那我有 2 個選擇。

  1. 把 TypeScript 範例轉成 JavaScript 使用。
  2. 把專案設定成支援 TypeScript 開發。

A. 把 TypeScript 範例 轉成 JavaScript 使用

把 TypeScript 註釋的型別刪除即可,修改後程式碼如下:

const [channels, setChannels] = useState([]);
...
const notificationListener = useRef();
const responseListener = useRef();

B. 把專案設定成支援 TypeScript 開發

  1. App.js 修改為 App.tsx
  2. 安裝 TypeScript 和必備的 Types
npm install --save-dev typescript @types/react @types/react-native
  1. 建立 tsconfig.json 文件。
    使用下列命令來初始化及建立文件。
npx tsc --init
  1. 更新 babel.config
module.exports = function(api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo'],
  };
};
  1. 確認所有檔案都使用 .tsx 副檔名。

為了將來與同事協作需要,我先使用 A. 把 TypeScript 範例 轉成 JavaScript 使用。

繼續看一下 IDE 的提示,發現有一些 library 未安裝,依照提示訊息點擊安裝。

import * as Device from 'expo-device';
...
import Constants from 'expo-constants';

試著運行 App,在 App.js 檔案出現以下錯誤。

File is not included in any tsconfig.json

嘗試使用 B 選項提到的初始化指令來解決。

npx tsc --init

初始化後仍舊顯示錯誤。

File is not included in any tsconfig.json

先略過這項錯誤。直接在 terminal 運行專案。

實體 Android 手機的 Expo Go 顯示錯誤 Log 如下:
https://ithelp.ithome.com.tw/upload/images/20240916/20151956VXjd2kdMHp.jpg
https://ithelp.ithome.com.tw/upload/images/20240916/20151956WrEKEmEgLA.jpg

爬文後,發現這個可能跟 Expo CLI 版本過時有關,明天再來繼續修復。
資料來源:stackoverflow - The legacy expo-cli does not support Node +17


上一篇
[Day 5] React Expo Notification API 功能
下一篇
[Day 7] macOS 安裝 Expo Notification library
系列文
跨平台協同:在 React Native 和 Kotlin 應用中實現無縫交互 -以 Notification 為例7
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言